package com.feng.gulimall.product.exception;

import com.feng.common.exception.BizCodeEnum;
import com.feng.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 全局异常处理
 * @author 丰
 * @date 2022/11/3 9:54
 * @version 1.0
 */
@Slf4j
//@ControllerAdvice(value = "com/feng/gulimall/product/controller")
//@ResponseBody
@RestControllerAdvice(basePackages = "com.feng.gulimall.product.controller")
public class ExceptionControllerAdvice {

    // 数据校验
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e){
        System.out.println(">>>>>>>>>>>>>>>>..");
        BindingResult bindingResult = e.getBindingResult();
        Map<String, Object> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item) -> {
            // 获取错误信息
            String message = item.getDefaultMessage();
            // 获取错误字段
            String name = item.getField();
            map.put(name, message);
        });
//        log.error(e.getMessage());
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", map);
    }

    // 所有异常
    @ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e){
        log.error(e.getMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
